package edu.neu.ecommerceplatform.controller;

import edu.neu.ecommerceplatform.dto.AddCartItemRequest;
import edu.neu.ecommerceplatform.dto.CartResponse;
import edu.neu.ecommerceplatform.dto.UpdateCartItemRequest;
import edu.neu.ecommerceplatform.service.CartService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/cart")
public class CartController {

    private final CartService cartService;

    @Autowired
    public CartController(CartService cartService) {
        this.cartService = cartService;
    }

    // In a real app with Spring Security, you would get the user ID like this:
    // public ResponseEntity<CartResponse> getCart(@AuthenticationPrincipal UserPrincipal principal) {
    //     CartResponse cart = cartService.getCart(principal.getId()); ...
    // For now, we'll pass it as a request parameter for demonstration.
    @GetMapping
    public ResponseEntity<CartResponse> getCart(@RequestParam Integer userId) {
        CartResponse cart = cartService.getCart(userId);
        return ResponseEntity.ok(cart);
    }

    @PostMapping("/items")
    public ResponseEntity<CartResponse> addItemToCart(@RequestParam Integer userId, @Valid @RequestBody AddCartItemRequest request) {
        CartResponse cart = cartService.addItemToCart(userId, request);
        return ResponseEntity.ok(cart);
    }

    @PutMapping("/items/{productId}")
    public ResponseEntity<CartResponse> updateItemInCart(@RequestParam Integer userId, @PathVariable Integer productId, @Valid @RequestBody UpdateCartItemRequest request) {
        CartResponse cart = cartService.updateItemInCart(userId, productId, request);
        return ResponseEntity.ok(cart);
    }

    @DeleteMapping("/items/{productId}")
    public ResponseEntity<CartResponse> removeItemFromCart(@RequestParam Integer userId, @PathVariable Integer productId) {
        CartResponse cart = cartService.removeItemFromCart(userId, productId);
        return ResponseEntity.ok(cart);
    }

    @DeleteMapping
    public ResponseEntity<Void> clearCart(@RequestParam Integer userId) {
        cartService.clearCart(userId);
        return ResponseEntity.noContent().build();
    }
} 